package com.lry.sso.client.filter;

import com.alibaba.fastjson.JSON;
import com.lry.sso.auth.common.bean.RequestInfoContext;
import com.lry.sso.auth.common.exception.AuthException;
import com.lry.sso.auth.common.util.AuthUtil;
import com.lry.sso.auth.common.util.HttpUtils;
import com.lry.sso.auth.common.util.SessionInfo;
import com.lry.sso.client.feign.AuthFeign;
import com.lry.sso.common.entity.response.Ret;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 请求拦截验证是否有token
 *
 * @author 李瑞益
 * @date 2020-02-13 10:45
 */
@Component
@WebFilter(urlPatterns = "/*")
@Order(Ordered.HIGHEST_PRECEDENCE)
@ConditionalOnProperty(name = "sso.auth.tokenFilter.enable",havingValue = "true",matchIfMissing = true)
public class AuthClientTokenFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(AuthClientTokenFilter.class);

    @Autowired
    private AuthFeign authFeign;

    /**
     *  过滤没有token的请求；
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        String token = AuthUtil.getTokenForUrl(req);
        HttpServletResponse res =(HttpServletResponse)response;
        logger.info("请求验证是否登录。。。");
        if (StringUtils.isEmpty(token)) {
            logger.info("无token（登录信息）");
            HttpUtils.writeResponse(res, HttpStatus.UNAUTHORIZED.value(),JSON.toJSONString(Ret.error(AuthException.AUTH_FAIL)));
            return;
        }
        SessionInfo sessionInfo = authFeign.parseToken(token);
        if (sessionInfo == null) {
            logger.info("token（登录信息）无效");
            HttpUtils.writeResponse(res, HttpStatus.UNAUTHORIZED.value(),JSON.toJSONString(Ret.error(AuthException.AUTH_FAIL)));
            return;
        }
        logger.info("登录信息:{}",sessionInfo);

        RequestInfoContext.set(sessionInfo);
        chain.doFilter(request,response);
    }
}
